package com.finals.finalsscreen.phone;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.finals.finalsscreen.app.BaseApplication;
import com.finals.finalsscreen.util.Util;

public class PhoneStateListen {

	BaseApplication mApplication;

	CallBroadcastReceiver mReceiver;

	MyPhoneStateListener mListener;

	public PhoneStateListen(BaseApplication mApplication) {
		this.mApplication = mApplication;
		mListener = new MyPhoneStateListener(mApplication, this);
		mReceiver = new CallBroadcastReceiver(mApplication, this);
	}

	public void setState(int state) {
		switch (state) {
		case CALL_STATE_OUTCALL:
			mApplication.showWindow();
			break;
		case CALL_STATE_RINGING:
			mApplication.showWindow();
			break;
		case CALL_STATE_IDLE:
			mApplication.closeWindow();
			break;
		default:
			break;
		}
	}

	public void InitCallListener() {
		// Finals 来电开始监听
		TelephonyManager manager = (TelephonyManager) mApplication.getSystemService(Context.TELEPHONY_SERVICE);
		try {
			manager.listen(mListener, PhoneStateListener.LISTEN_CALL_STATE);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(Util.TAG, "监听来电失败");
		}
		// Finals 去电
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
		mApplication.registerReceiver(mReceiver, mFilter);
	}

	/**
	 * 释放来电监听
	 */
	public void ReleaseCallListener() {
		TelephonyManager manager = (TelephonyManager) mApplication.getSystemService(Context.TELEPHONY_SERVICE);
		try {
			manager.listen(mListener, PhoneStateListener.LISTEN_NONE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		mApplication.unregisterReceiver(mReceiver);
	}

	static final int CALL_STATE_RINGING = 0;

	static final int CALL_STATE_IDLE = 1;

	static final int CALL_STATE_OUTCALL = 2;

	static final int CALL_STATE_OFFHOOK = 3;
}
